  <template>
  <div class="user-page">
    <h2>欢迎来到我的美食空间</h2>
    <div class="user-info">
      <div class="user-avatar">
        <img :src="userInfo.avatar" alt="" />
      </div>

      <div class="user-main">
        <h1>{{ userInfo.name }}</h1>

        <span class="info">
          <em>{{ createdAt }} 加入了美食杰</em>
          <span  v-if="isOwner">
            |
            <router-link :to="{ name: 'useredit' }">
              编辑个人资料
            </router-link>
          </span>
        </span>

        <h3 class="info">个人简介：{{ userInfo.sign }}</h3>

        <div class="tools" v-show="!isOwner">
          <a
            href="javascript:;"
            :class="{
              'follow-at': !userInfo.isFollowing,
              'no-follow-at': userInfo.isFollowing,
            }"
            @click="toggleFollow"
          >
            {{ userInfo.isFollowing ? "已关注" : "+ 关注" }}
          </a>
        </div>
      </div>

      <ul class="user-more-info">
        <li>
          <div>
            <span>关注</span>
            <strong>{{ userInfo.following_len }}</strong>
          </div>
        </li>
        <li>
          <div>
            <span>粉丝</span>
            <strong>{{ userInfo.follows_len }}</strong>
          </div>
        </li>
        <li>
          <div>
            <span>收藏</span>
            <strong>{{ userInfo.collections_len }}</strong>
          </div>
        </li>
        <li>
          <div>
            <span>发布菜谱</span>
            <strong>{{ userInfo.work_menus_len }}</strong>
          </div>
        </li>
      </ul>
    </div>

    <el-tabs class="user-nav" v-model="activeTab" @tab-click="tabChange">
      <el-tab-pane label="作品" name="works"></el-tab-pane>
      <el-tab-pane label="粉丝" name="fans"></el-tab-pane>
      <el-tab-pane label="关注" name="following"></el-tab-pane>
      <el-tab-pane label="收藏" name="collection"></el-tab-pane>
    </el-tabs>

    <div class="user-info-show">
      <!-- 渲染子路由组件 -->
      <router-view :list="listInfo.list" :activeTab="activeTab"></router-view>
    </div>
  </div>
</template>
  
<script>
import { getUserInfo, toggleFollowing } from "@/service";
import {
  getMenus,
  getCollectionMenu,
  getFollowingList,
  getFansList,
} from "@/service";

const requestObj = {
  works: async (params) => {
    let data = (await getMenus(params)).data;
    data.flag = "works";
    return data;
  },
  fans: async (params) => {
    let data = (await getFansList(params)).data;
    data.flag = "fans";
    return data;
  },
  following: async (params) => {
    let data = (await getFollowingList(params)).data;
    data.flag = "following";
    return data;
  },
  collection: async (params) => {
    let data = (await getCollectionMenu(params)).data;
    data.flag = "collection";
    return data;
  },
};

export default {
  name: "Space",

  data() {
    return {
      userInfo: {},
      isOwner: false,
      activeTab: "works",
      listInfo: {},
    };
  },

  computed: {
    createdAt() {
      return this.userInfo.createdAt?.slice(0, 10);
    },
  },

  watch: {
    $route: {
      async handler() {
        const { userId } = this.$route.query;
        this.isOwner = !userId || userId === this.$store.state.userInfo.userId; // 判断是否为当前用户空间

        // 1. 获取用户信息
        if (this.isOwner) {
          this.userInfo = this.$store.state.userInfo;
        } else {
          const res = await getUserInfo({ userId });
          this.userInfo = res.data;
        }
        // console.log(this.userInfo);

        // 2. 根据路由信息，更改 activeTab 的状态; 发送请求，获取数据
        // console.log(this.$route.name);
        this.activeTab = this.$route.name;
        this.getList();
      },
      immediate: true,
    },
  },

  methods: {
    /* 关注切换 */
    toggleFollow() {
      toggleFollowing({ followUserId: this.userInfo.userId }).then((res) => {
        this.userInfo = res.data;
      });
    },
    /* tab 栏切换 */
    tabChange() {
      this.listInfo = {}; // 切换前，数据置空
      this.$router.push({
        name: this.activeTab,
        // 保留之前的 query（userId）信息
        query: {
          ...this.$route.query,
        },
      });
    },
    /* 请求列表信息：
      listInfo 为最后一次 ajax请求回来的数据（滞后了，顺序可能与点击顺序不一样）
        - 为返回的数据添加标识，data.flag === activeTab时，在改变 listInfo 的值
    */
    async getList() {
      let data = await requestObj[this.activeTab]({
        userId: this.userInfo.userId,
      });
      if (data.flag === this.activeTab) {
        this.listInfo = data;
      }
    },
  },
};
</script>
  
<style>
.user-page h2 {
  text-align: center;
  margin: 20px 0;
}
.user-info {
  height: 210px;
  background-color: #fff;
  display: flex;
}
.user-avatar {
  width: 210px;
  height: 210px;
}
.user-avatar img {
  width: 100%;
  height: 100%;
}
.user-main {
  width: 570px;
  padding: 20px;
  position: relative;
}
.user-main h1 {
  font-size: 24px;
  color: #333;
  line-height: 44px;
}
.info {
  font-size: 12px;
  line-height: 22px;
  color: #999;
}
.info-empty {
  width: 100%;
  min-height: inherit;
  /* display: flex;
  align-items: center;
  justify-content: center; */
}
.info-empty p {
  text-align: center;
  font-size: 18px;
}
.info a {
  color: #999;
}
.user-main .tools {
  position: absolute;
  right: 20px;
  top: 20px;
  vertical-align: top;
}
.tools a {
  display: inline-block;
  padding: 3px 0;
  width: 50px;
  color: #fff;
  text-align: center;
}
a.follow-at {
  background-color: #ff3232;
}
a.no-follow-at {
  background-color: #999;
}
.user-more-info {
  width: 190px;
  overflow: hidden;
  padding: 20px 5px 0 0;
}
.user-more-info li {
  width: 81px;
  height: 81px;
  border-radius: 32px;
  border-bottom-right-radius: 0;
  margin: 0 8px 8px 0;
  float: left;
}
.user-more-info li div {
  display: block;
  height: 81px;
  width: 81px;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.2) inset;
  border-radius: 32px;
  border-bottom-right-radius: 0;
}
li div span {
  color: #999;
  display: block;
  line-height: 20px;
  padding: 14px 0 0 14px;
}
li div strong {
  display: block;
  font-size: 18px;
  color: #ff3232;
  font-family: Microsoft Yahei;
  padding-left: 14px;
  line-height: 32px;
}
.user-nav {
  margin: 20px 0 20px 0;
}
.user-info-show {
  min-height: 300px;
  background-color: #fff;
  padding-top: 20px;
}

.el-tabs__item.is-active {
  color: #ff3232;
}
.el-tabs__active-bar {
  background-color: #ff3232;
}
.el-tabs__nav-wrap::after {
  background-color: transparent;
}
</style>